package com.example.werewolf.service.impl.role;

import com.alibaba.fastjson2.JSONObject;
import com.example.werewolf.common.ActionType;
import com.example.werewolf.entity.Event;
import com.example.werewolf.entity.GamePhase;
import com.example.werewolf.entity.Player;
import com.example.werewolf.model.ActionSkill;
import com.example.werewolf.model.GameChatResp;
import com.example.werewolf.service.ActionStrategy;
import com.example.werewolf.utils.PrintUtils;
import com.example.werewolf.utils.RoleUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

@Component
public class WitchActionStrategy implements ActionStrategy {

    @Override
    public ActionSkill execute(List<Player> players, List<Player> actionPlayers,
                               GamePhase phase, List<Event> publicEvents, SseEmitter emitter) throws IOException {
        if (actionPlayers.isEmpty()) return ActionSkill.builder()
                .actionType(ActionType.WITCH_ACTION)
                .witchTargetNum(null)
                .build();

        Player witch = actionPlayers.get(0); // 女巫唯一
        Player killedPlayer = RoleUtils.getKilledPlayer(players);
        if (killedPlayer == null) {
            PrintUtils.printSystem(emitter, "");
        }
        System.out.println("🧪 女巫行动：请选择救（1）或毒（2）或不行动（-1）");

        String witchPrompt = buildWitchPrompt(witch, killedPlayer);
        // 女巫根据刀人和道具情况记录
        PrintUtils.printSystem(emitter, witchPrompt);

        // 女巫具体行动（救1，毒2，不行动-1）
        String chat = witch.chat(witchPrompt);
        GameChatResp resp = parseResponse(chat);
        PrintUtils.printPlayer(emitter, witch, resp.getContent());

        Integer targetNum = resp.getTargetNum();
        Integer target = resp != null ? targetNum == null ? -1 : targetNum : -1;
        System.out.println("女巫选择：" + (target == -1 ? "放弃使用能力" : "目标 " + target));

        String operate = "";
        // 女巫行动完，主持人记录
        // 救：killedPlayer -> isKilled = fales;
        // 毒：targetNum -> targetPlayer -> isPoison = true;
        // 不操作：null
        if (resp.getOperateType() == -1) {
            // 无行动
            operate = "无操作";
        } else if (resp.getOperateType() == 1) {
            // 救人
            operate = "解救";
            players.stream()
                    .filter(user -> user.getId() == target)
                    .findFirst()
                    .ifPresent(user -> user.setKilled(false));
        } else if (resp.getOperateType() == 2) {
            // 毒人
            operate = "毒杀";
            players.stream()
                    .filter(user -> user.getId() == target)
                    .findFirst()
                    .ifPresent(user -> user.setKilled(false));
        }

        // 记录女巫的私有消息
        Player targetPlayer = RoleUtils.getTargetPlayer(players, target);
        String acceptPlayer = "女巫";
        String message = "【主持人 + 女巫】：女巫" + operate + ":" + targetPlayer.getId();
        PrintUtils.printSystem(emitter, message);

        witch.addEvent(Event.builder()
                .description(acceptPlayer)
                .affectedPlayer(Collections.singletonList(witch.getId()))
                .build()
        );

        return ActionSkill.builder()
                .actionType(ActionType.WITCH_ACTION)
                .isPoison(false)
                .witchTargetNum(target)
                .build();
    }

    private String buildWitchPrompt(Player witch, Player killedPlayer) {
        String prompt = "";
        boolean isKillWitch = killedPlayer.getId() == witch.getId();

//        boolean hasAntidote = Math.random() > 0.5;
//        boolean hasPoison = Math.random() > 0.5;
        boolean hasAntidote = true;
        boolean hasPoison = true;
        /*
        女巫有解药时才能知道刀口；女巫不能自救
         */
        if (hasAntidote) {
            prompt += "今晚" + killedPlayer.getId() + "玩家被刀，";
            if (isKillWitch) {
                prompt += "你不能自救，";
            } else {
                prompt += "你可以选择使用解药，";
            }
        }
        if (hasPoison) {
            prompt += "你可以使用毒药，";
        }
        if (!hasPoison && !hasAntidote) {
            prompt += "你没有道具，无法使用技能，";
        }
        prompt += "请根据你的技能状态和你的信息，选择是否使用技能。请选择救（1）或毒（2）或不行动（-1），在响应中添加operateType字段。";
        return prompt;
    }

    private GameChatResp parseResponse(String json) {
        try {
            return JSONObject.parseObject(json, GameChatResp.class);
        } catch (Exception e) {
            System.err.println("解析女巫响应失败: " + e.getMessage());
            return null;
        }
    }
}
